#pragma once

#include<iostream>
#include<string>
#include<cstring>
#include<functional>
#include<sys/types.h>
#include<sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>

#include"Log.hpp"
#include "Connection.hpp"
#include"Comm.hpp"
#include"HandlerConnection.hpp"

//创建连接，并且添加到tcp->connection

class Accepter
{
public:
    Accepter(){}
    ~Accepter(){}

    //一直有连接到来
    void AcceptConnection(Connection*conn)
    {
        errno=0;
        while(true)
        {
            struct sockaddr_in peer;
            socklen_t len=sizeof(peer);
            int sockfd=::accept(conn->GetConnFd(),(struct sockaddr*)&peer,&len);
            //获取连接，添加到connct
            if(sockfd>0)
            {
                int peerport=peer.sin_port;
                std::string peerip=inet_ntoa(peer.sin_addr);
                SetNonBlock(sockfd);
                lg.LogMessage(Info,"accept a new connction,fd %d,%s:%d",conn->GetConnFd(),peerip.c_str(),peerport);
                //绑定处理的方法
                auto recver=std::bind(&HandlerConnection::Recver,std::placeholders::_1);
                auto sender=std::bind(&HandlerConnection::Sender,std::placeholders::_1);
                auto excepter=std::bind(&HandlerConnection::Excepter,std::placeholders::_1);

                Connection* normal_conn=ConnectionFactory::BulidNormalConnction(sockfd,recver,sender,excepter,EPOLLIN|EPOLLOUT,conn->_R);
                conn->_R->AddConnection(normal_conn);
            }
            else
            {
                if(errno==EAGAIN)
                    break;
                else if(errno==EINTR)
                    continue;
                else
                {
                    lg.LogMessage(Warning,"accept a new link error,%d:%s",errno,strerror(errno));
                    break;
                }
            }
        }
    }
private:

};